import csv
import json
from collections import Counter
import os

jsonpath='D:/Project/3d-force-graph-master/example/directional-links-particles/qsj.json'
jsonoupt=open(jsonpath,'w',encoding='UTF-8')
with open('D:/temp/qjs.csv','r',encoding='UTF-8') as f:
    f_csv=csv.reader(f)
    nodes=[] #叶子节点
    links=[]
    tempnodes=[]
    csvidx=0
    for row in f_csv:
        if csvidx==0: 
            csvidx+=1
            continue
        node={
            "id":row[0],
            "prefecture":row[1],
            "note":row[2],
            "nodename":row[3],
            "name2":row[4],
            "name3":row[5],
            "place":row[6],
            "decription":row[10],
            "link":row[12],
            "group":-1,
            "target":-1,
            "nodesize":4
        }
        nodes.append(node)
    nodeCount=0
    parentnodes=[] # 父节点，无实际数据
    rootkey=list(Counter(list(map(lambda node:node["prefecture"],nodes))).keys())
    #生成县节点
    for idx in range(len(rootkey)):
        rootnode={
            "id":nodeCount+1+idx,
            "nodename":rootkey[idx],
            "target":-1,
            "group":nodeCount+1+idx,
            "nodesize":16
        }
        parentnodes.append(rootnode)
    # 生成村节点
    nodeCount=len(parentnodes)
    rootkey=(list(Counter(list(map(lambda node:node["place"]+","+node["prefecture"],nodes))).keys()))
    for idx in range(len(rootkey)):
        contents=rootkey[idx].split(',')
        parentnodeid=list(filter(lambda node: node["nodename"]==contents[1],parentnodes))[0]["id"]
        rootnode={
            "id":nodeCount+1+idx,
            "target":parentnodeid,
            "nodename":contents[0],
            "group":parentnodeid,
            "nodesize":8
        }
        parentnodes.append(rootnode)
    #修改叶子节点target,id
    for idx in range(len(nodes)):
        nodes[idx]["id"]=len(parentnodes)+idx+1
        parentnode=list(filter(lambda node:node["nodename"]==nodes[idx]["place"],parentnodes))[0]
        nodes[idx]["target"]=parentnode["id"]
        nodes[idx]["group"]=parentnode["target"]
    parentnodes.extend(nodes)

    #生成links
    links=[]
    for node in parentnodes:
        if node["target"]>0:
            links.append({
                "source":node["id"],
                "target":node["target"]
            })
    nodeinformations={
        "nodes":parentnodes,
        "links":links
    }
    json.dump(nodeinformations,jsonoupt,ensure_ascii=False)